import * as Matter from 'matter-js';
import { App } from '../system/App';

export class Diamond {
  constructor(x, y) {
    console.log('Diamond', x, y)

    this.width = App.config.basket.rim.width;
    this.height = App.config.basket.rim.height;
    this.board = App.config.basket.board;
    this.rim = App.config.basket.rim;
    this.r = App.config.basket.rim.r;

    this.createSprite(x, y);

    this.dx = 5;
    // App.app.ticker.add(this.update, this);
  }

  createSprite(x, y) {
    this.sprite = App.sprite("diamond");
    this.sprite.x = 0;
    this.sprite.y = this.board.height - this.r * 2;
    this.sprite.width = 30;
    this.sprite.height = 30;
  }

  // update() {
  //     if (this.sprite) {
  //         Matter.Body.setPosition(this.body, {x: this.sprite.width / 2 + this.sprite.x + this.sprite.parent.x, y: this.sprite.height / 2 + this.sprite.y + this.sprite.parent.y});
  //     }
  // }

  createBody() {
    // this.body = Matter.Bodies.rectangle(this.sprite.width / 2 + this.sprite.x + this.sprite.parent.x, this.sprite.height / 2 + this.sprite.y + this.sprite.parent.y, this.sprite.width, this.sprite.height, {
    //   friction: 0,
    //   isStatic: true,
    //   render: {fillStyle: '#060a19'}
    // });

    this.body = Matter.Bodies.circle(
      this.rim.width / 2 || (this.sprite.parent.x + this.width) / 2 + this.r * 2,
      this.sprite.parent.y + this.board.height - this.r * 2,
      this.r,
      {
        isStatic: true,
        render: {
          fillStyle: 'green',
          strokeStyle: 'black'
        }
      }
    );
    this.body.isSensor = true;
    this.body.gameDiamond = this;
    Matter.World.add(App.physics.world, this.body);
  }

  move(dx) {
    if (dx > 0) {
      if (this.body && this.body.position.x < this.rim.width - this.r * 2) {
        Matter.Body.setPosition(this.body, {x: this.body.position.x + dx, y: this.body.position.y});
      }
    } else {
      if (this.body && this.body.position.x  > 0 - App.config.basket.board.width) {
        Matter.Body.setPosition(this.body, {x: this.body.position.x + dx, y: this.body.position.y});
      }
    }
  }

  // [14]
  destroy() {
    if (this.sprite) {
      // App.app.ticker.remove(this.update, this);
      Matter.World.remove(App.physics.world, this.body);
      this.sprite.destroy();
      this.sprite = null;
    }
  }
}